package com.hengpeng.itfin.persist.impl;

import java.util.Date;
import java.util.List;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;

import com.hengpeng.common.persist.AbstractDao;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.constants.QueryConstants.LockType;
import com.hengpeng.itfin.persist.BorrowInfoDao;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.BorrowInfo.BorrowStatus;
import com.hengpeng.itfinbase.persist.BorrowInfo.InputStatus;

@Repository
@Lazy
public class BorrowInfoDaoImpl extends AbstractDao<BorrowInfo> implements BorrowInfoDao
{
	@Override
	public List<BorrowInfo> lockScheduleList()
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		query.eq("status", BorrowStatus.SCHEDULED);
		query.le("bidOpenTime", new Date());
		return super.findAllByDynamicQuery(query, LockType.LOCK_WAIT);
	}

	@Override
	public List<BorrowInfo> queryBorrowList(BorrowStatus status)
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		query.eq("status", status);
		return super.findAllByDynamicQuery(query);
	}

	@Override
	public List<BorrowInfo> getUnAddBidList()
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		query.inArray("status", new BorrowStatus[] { BorrowStatus.SCHEDULED, BorrowStatus.RAISE, BorrowStatus.END });
		query.inArray("inputStatus", new InputStatus[] { InputStatus.WAIT, InputStatus.FAILED });
		return super.findAllByDynamicQuery(query);
	}

	@Override
	public List<BorrowInfo> endRaistList()
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		query.eq("status", BorrowStatus.RAISE);
		query.le("bidStopTime", new Date());
		return super.findAllByDynamicQuery(query, LockType.LOCK_WAIT);
	}

	@Override
	public void updateList(List<BorrowInfo> infoList)
	{
		super.updateAll(infoList);
	}

	@Override
	public void updateInfo(BorrowInfo borrow)
	{
		super.update(borrow);
	}

	public BorrowInfo lockInfo(Long id)
	{
		return super.lockById(id);
	}

	@Override
	public BorrowInfo getBorrowInfo(Long id, BorrowStatus status)
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		query.eq("id", id);
		query.eq("status", status);
		List<BorrowInfo> list = super.findAllByDynamicQuery(query, BorrowInfo.class);
		return list == null || list.size() < 0 ? null : list.get(0);
	}

}
